package com.bq.server.enumeration;


import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

import java.util.concurrent.ConcurrentMap;

/**
 * 枚举缓存
 * @author: ChenSH
 * @date: Create by in 下午5:22 2018/7/27
 */
public class EnumerationCache {

    private static final ConcurrentMap<Class<? extends Enumeration>, ImmutableMap<Integer, Enumeration>> cache = Maps.newConcurrentMap();


    public static <E extends Enumeration> E valueOf(Class<E> enumClass, Integer value) {
        Enumeration enumeration = getEnumValues(enumClass).get(value);
        return enumClass.cast(enumeration);
    }

    public static <E extends Enumeration> ImmutableMap<Integer, Enumeration> getEnumValues(Class<E> enumClass) {
        return cache.computeIfAbsent(enumClass,
                valueClass -> {
                    ImmutableMap.Builder<Integer, Enumeration> builder = ImmutableMap.builder();
                    Enumeration[] enumConstants = valueClass.getEnumConstants();
                    for (Enumeration enumConstant : enumConstants) {
                        builder.put(enumConstant.value(), enumConstant);
                    }
                    return builder.build();
                });
    }
}
